package adfc2.tasks;

import adfc2.actions.LeaveWorkshopAction;
import adfc2.actions.StepAction;
import adfc2.core.Action;
import adfc2.core.Creature;
import adfc2.core.Pathfinder;
import adfc2.core.Task;
import adfc2.entities.Workshop;

import static adfc2.core.World.*;

public class MoveTask extends Task {

    public final int toxy;
    public final boolean near;

    int[] path;
    int pathpos;

    public MoveTask(Creature actor, int toxy, boolean near) {
        super(actor);
        this.toxy = toxy;
        this.near = near;
    }

    @Override
    public Action nextAction() {
        if (actor.getXY() == toxy) {
            completed();
            return null;
        } else if (actor.container != null) {
            if (actor.container instanceof Workshop) {
                return new LeaveWorkshopAction(actor);
            } else {
                failed();
                return null;
            }
        } else {
            if (path == null || !passable(world().blocks[path[pathpos]])) {
                path = Pathfinder.findPath(actor.getXY(), toxy, near);
                pathpos = 1;
                if (path == null) {
                    failed();
                    return null;
                }
            }
            int stepxy = path[pathpos];
            pathpos++;
            return new StepAction(actor, stepxy);
        }
    }

    @Override
    public String shortName() {
        return "move";
    }

    @Override
    public String toString() {
        return "MoveTask[" + xy2x(toxy) + "," + xy2y(toxy) + "]";
    }
}
